/*
Licensed to the Apache Software Foundation (ASF) under one
or more
 contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you
under
the
Apache
License, Version 2.0 (the
"License"); you may not use this file except in compliance
with
the
License
.  You
may
obtain
a copy
of the
License at

  http
  ://www.apache.org/licenses/LICENSE-2.0

Unless
required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS"
 BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND,
either
express
 or
 implied.  See the License for the
specific language governing permissions and limitations
under
the
License.
 */
package
        com.wondertek.mist.plugins;

import
        java.io.File;
import
        java.io.FileInputStream;
import
        java.io.FileOutputStream;
import
        java.io.InputStream;
import
        java.util.ArrayList;
import
        java.util.HashMap;
import
        java.util.List;
import
        java.util.Map;

import
        org.apache.cordova.CordovaWebView;
import
        org.apache.cordova.api.CallbackContext;
import
        org.apache.cordova.api.CordovaInterface;
import
        org.apache.cordova.api.CordovaPlugin;
import
        org.apache.cordova.api.PluginResult;
import
        org.json.JSONArray;
import
        org.json.JSONException;
import
        org.json.JSONObject;

import
        android.app.Activity;
import
        android.app.Dialog;
import
        android.content.ContentResolver;
import
        android.content.Intent;
import
        android.database.Cursor;
import
        android.graphics.Bitmap;
import
        android.graphics.BitmapFactory;
import
        android.media.ExifInterface;
import
        android.net.Uri;
import
        android.os.Environment;
import
        android.provider.MediaStore;
import
        android.util.Log;
import
        android.widget.Button;
import
        android.widget.Toast;

import
        com.wondertek.mist.photo.AppConfig;
import
        com.wondertek.mist.photo.FileUtils;
import
        com.wondertek.mist.photo.OnUploadProcessListener;
import
        com.wondertek.mist.photo.UpIoadFileUtil;
import
        com.wondertek.mist.utils.StringUtils;

/**
 * 多张图片上传
 */
public
class
CanvasPicture extends CordovaPlugin {

    private static final String TAG = "CanvasPicture";
    private Activity ac = null;
    private File file = null;
    private CallbackContext mCallbackContext = null;
    private List<String> drr = new ArrayList<String>();


    private String latitude = "0.0";//纬度
    private String longitude = "0.0";//经度
    private String altitude = "0.0"; //海拔高度
    private String altitudeRef = "0.0"; //海拔高度


    private String subDir = "";
    private String gonghao = "cfub";
    private String uploadUrl = null;

    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        ac = cordova.getActivity();
        Log.i(TAG, "------initialize。。。。");
    }

    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
        mCallbackContext = callbackContext;

        JSONObject json = (JSONObject) args.getJSONObject(0);

        Log.i(TAG, "action---->" + action);
        Log.i(TAG, json.toString());

        //uploadUrl = "http://192.168.1.105:8080/jiangxin-web/goods/testAndroid";//args.getString(0);
        uploadUrl = args.getString(0);
        if (action.equals("takePicture")) //拍照
        {
            try {
                if (!Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    Toast.makeText(ac, "无SD卡或SD卡无法使用", 1).show();
                } else {
                    new File(AppConfig.TEMP_DIR).mkdir();
                    file = new File(AppConfig.TEMP_DIR + gonghao + "_" + System.currentTimeMillis() + ".png");// 通过路径创建保存文件
                    Uri imageFileUri = Uri.fromFile(file); // 获取文件的Uri
                    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 跳转到相机Activity
                    it.putExtra(MediaStore.EXTRA_OUTPUT,
                            imageFileUri); // 告诉相机拍摄完毕输出图片到指定的Uri
                    cordova.startActivityForResult(
                            (CordovaPlugin) CanvasPicture.this, it, 1);
                }
            } catch (Exception e) {
                e.printStackTrace();
                callbackContext.error("Illegal Argument Exception");
                PluginResult r = new PluginResult(PluginResult.Status.ERROR);
                callbackContext.sendPluginResult(r);
            }

        } else// if (action.equals("selectPicture")) //选择照片
        {

            try {
                if (!Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    Toast.makeText(ac, "无SD卡或SD卡无法使用", 1).show();
                } else {
                    new File(AppConfig.TEMP_DIR).mkdir();
                    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 调用android的图库
                    i.putExtra("return-data", true);

                    cordova.startActivityForResult((CordovaPlugin) CanvasPicture.this, i, 2);

                    //Log.i(TAG, "------选择相册开始。。。。");
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                callbackContext.error("Illegal Argument Exception");
                PluginResult r = new PluginResult(PluginResult.Status.ERROR);
                callbackContext.sendPluginResult(r);
            }

        }
        return true;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
            if (requestCode == 1) {
                // 拍照
                if (file.exists()) {
                    try {
                        int angle = AppConfig.readPictureDegree(file.getAbsolutePath());
                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                        bitmapOptions.inSampleSize = 3;
                        Bitmap bitmap = BitmapFactory.decodeFile(
                                file.getAbsolutePath(), bitmapOptions);
                        bitmap = AppConfig.rotaingImageView(angle, bitmap);
                        FileOutputStream out;
                        out = new FileOutputStream(file);
                        // /bitmap.compress(Bitmap.CompressFormat.PNG, 100,
                        // out);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 80, out);
                        out.flush();
                        out.close();
                        Toast.makeText(ac, "开始上传图片，请稍等", Toast.LENGTH_SHORT).show();
                        startUp();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (requestCode == 2 && data != null) {
                try {
                    Toast.makeText(ac, "开始上传图片，请稍等", Toast.LENGTH_SHORT).show();
                    Uri uri = data.getData();
                    ContentResolver cr = ac.getContentResolver();
                    Cursor cursor = cr.query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    file = new File(cursor.getString(1));
                    InputStream inStream = new FileInputStream(file); // 读入原文件
                    String suffix = file.getName().substring(
                            file.getName().lastIndexOf(".") + 1);
                    file = new File(AppConfig.TEMP_DIR + gonghao + "_"
                            + +System.currentTimeMillis() + "." + suffix);
                    FileOutputStream fs = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int length = 0;
                    int bytesum = 0;
                    int byteread = 0;
                    while ((byteread = inStream.read(buffer)) != -1) {
                        bytesum += byteread; // 字节数 文件大小
                        fs.write(buffer, 0, byteread);
                    }
                    inStream.close();
                    fs.close();
                    AppConfig.compressImage(file);
                    startUp();
                    // /qie(file);
                    // Bitmap bitmap =
                    // StaticConst.compressImageFromFile(StaticConst.DIR +
                    // File.separator + "temp." + suffix,
                    // ShowBabyInfoActivity.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } else {
            FileUtils.delAllFile(AppConfig.ZIP_DIR);
        }
    }

    private void startUp() {
        //File zipFile = FileUtils.zipAllPicByPath(AppConfig.TEMP_DIR, "m2zip");
        //FileUtils.delAllFile(AppConfig.ZIP_DIR);

        //file.getPath();
        //file.getAbsolutePath();
        String filePath = file.getPath();
        Log.i(TAG, "filePath====" + filePath);
        getPhotoParam(filePath);

        Map<String, String> param = new HashMap<String, String>();

        param.put("latitude", latitude); //纬度
        param.put("longitude", longitude);//经度
        param.put("altitude", altitude); //海拔高度
        //param.put("subDir", subDir);
        UpIoadFileUtil upIoadFileUtil = new UpIoadFileUtil(uploadUrl, file,
                new OnUploadProcessListener() {
                    @Override
                    public void onUploadDone(final String result) {
                        // 回调结果给javascript
                        cordova.getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                try {
                                    mCallbackContext.success(result);
                                    FileUtils.delAllFile(AppConfig.TEMP_DIR);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    System.out.println(e.toString());
                                }
                            }
                        });
                    }

                    @Override
                    public void initUpload() {
                        // Toast.makeText(cordova.getActivity(), "图片开始上传，请稍等",
                        // Toast.LENGTH_SHORT).show();
                    }

                }, param);
        upIoadFileUtil.StartUpIoadFile();
    }

    /*
     * 根据文件路径获取照片的信息
     */
    private void getPhotoParam(String filePath) {

        try {
            ExifInterface exifInterface = new ExifInterface(filePath);
            String orientation = exifInterface.getAttribute(ExifInterface.TAG_ORIENTATION); //旋转角度，整形表示，在ExifInterface中有常量对应表示
            String dateTime = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);//拍摄时间，取决于设备设置的时间
            String make = exifInterface.getAttribute(ExifInterface.TAG_MAKE);//设备品牌
            String model = exifInterface.getAttribute(ExifInterface.TAG_MODEL);//设备型号，整形表示，在ExifInterface中有常量对应表示
            String flash = exifInterface.getAttribute(ExifInterface.TAG_FLASH);//闪光灯
            String imageLength = exifInterface.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);//图片高度
            String imageWidth = exifInterface.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);//图片宽度
            latitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);//纬度
            if (StringUtils.isBlank(latitude)) {
                latitude = "0.0";
            }
            longitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);//经度
            if (StringUtils.isBlank(longitude)) {
                longitude = "0.0";
            }
            String latitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);//纬度名（N or S）
            String longitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);//经度名（E or W）
            String exposureTime = exifInterface.getAttribute(ExifInterface.TAG_EXPOSURE_TIME);//曝光时间
            String aperture = exifInterface.getAttribute(ExifInterface.TAG_APERTURE);//光圈值
            String isoSpeedRatings = exifInterface.getAttribute(ExifInterface.TAG_ISO);//ISO感光度
            ///String dateTimeDigitized = exifInterface.getAttribute(ExifInterface.TAG_DATETIME_DIGITIZED);  //数字化时间
            ///String subSecTime = exifInterface.getAttribute(ExifInterface.TAG_SUBSEC_TIME);
            ///String subSecTimeOrig = exifInterface.getAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIG);
            ///String subSecTimeDig = exifInterface.getAttribute(ExifInterface.TAG_SUBSEC_TIME_DIG);
            altitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_ALTITUDE); //海拔高度
            if (StringUtils.isBlank(altitude)) {
                altitude = "0.0";
            }
            String altitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF); //海拔高度
            String gpsTimeStamp = exifInterface.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP);//日期戳
            String gpsDateStamp = exifInterface.getAttribute(ExifInterface.TAG_GPS_DATESTAMP); //白平衡
            String whiteBalance = exifInterface.getAttribute(ExifInterface.TAG_WHITE_BALANCE);//焦距
            String focalLength = exifInterface.getAttribute(ExifInterface.TAG_FOCAL_LENGTH);
            String processingMethod = exifInterface.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD);//用于定位查找的全球定位系统处理方法

            Log.i(TAG, "orientation=" + orientation);
            Log.i(TAG, "dateTime=" + dateTime);
            Log.i(TAG, "make=" + make);
            Log.i(TAG, "model=" + model);
            Log.i(TAG, "flash=" + flash);
            Log.i(TAG, "imageLength=" + imageLength);
            Log.i(TAG, "imageWidth=" + imageWidth);
            Log.i(TAG, "latitude=" + latitude);
            Log.i(TAG, "longitude=" + longitude);
            Log.i(TAG, "latitudeRef=" + latitudeRef);
            Log.i(TAG, "longitudeRef=" + longitudeRef);
            Log.i(TAG, "exposureTime=" + exposureTime);
            Log.i(TAG, "aperture=" + aperture);
            Log.i(TAG, "isoSpeedRatings=" + isoSpeedRatings);
            //Log.i(TAG, "dateTimeDigitized=" + dateTimeDigitized);
            //Log.i(TAG, "subSecTime=" + subSecTime);
            //Log.i(TAG, "subSecTimeOrig=" + subSecTimeOrig);
            //Log.i(TAG, "subSecTimeDig=" + subSecTimeDig);
            Log.i(TAG, "altitude=" + altitude);
            Log.i(TAG, "altitudeRef=" + altitudeRef);
            Log.i(TAG, "gpsTimeStamp=" + gpsTimeStamp);
            Log.i(TAG, "gpsDateStamp=" + gpsDateStamp);
            Log.i(TAG, "whiteBalance=" + whiteBalance);
            Log.i(TAG, "focalLength=" + focalLength);
            Log.i(TAG, "processingMethod=" + processingMethod);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 新开线程对读取到的图片列表处理，不然会堵塞UI线程
     */
    private Runnable runnable = new Runnable() {
        public void run() {
            try {
                for (int i = 0; i < drr.size(); i++) {
                    File f_drr = new File(drr.get(i));
                    InputStream inStream = new FileInputStream(f_drr); // 读入原文件
                    String suffix = f_drr.getName().substring(
                            f_drr.getName().lastIndexOf(".") + 1);
                    file = new File(AppConfig.ZIP_DIR + i + "_" + gonghao + "_"
                            + System.currentTimeMillis() + "." + suffix);
                    FileOutputStream fs = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int length = 0;
                    int bytesum = 0;
                    int byteread = 0;
                    while ((byteread = inStream.read(buffer)) != -1) {
                        bytesum += byteread; // 字节数 文件大小
                        fs.write(buffer, 0, byteread);
                    }
                    inStream.close();
                    fs.flush();
                    fs.close();
                    AppConfig.compressImage(file);
                }

                // 开始上传图片
                startUp();
                // Bitmap bitmap =
                // StaticConst.compressImageFromFile(StaticConst.DIR +
                // File.separator + "temp." + suffix,
                // ShowBabyInfoActivity.this);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.toString());
            }
        }
    };

}